import winreg as reg
from .. import config

def set_windows_proxy(enable=True, proxy_server=f"127.0.0.1:{config.PROXY_PORT}", override_exceptions=None):
    """
    修改 Windows 的系统代理设置。
    
    :param enable: 是否启用代理
    :param proxy_server: 代理地址，格式为 "host:port"
    :param override_exceptions: 不使用代理的例外地址列表，例如 ["localhost", "127.0.0.1"]
    """
    if override_exceptions is None:
        override_exceptions = ["localhost", "127.0.0.1"]

    try:
        INTERNET_SETTINGS = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

        with reg.OpenKey(reg.HKEY_CURRENT_USER, INTERNET_SETTINGS, 0, reg.KEY_ALL_ACCESS) as key:
            # 启用/禁用代理
            reg.SetValueEx(key, 'ProxyEnable', 0, reg.REG_DWORD, 1 if enable else 0)

            if enable:
                # 设置代理服务器
                reg.SetValueEx(key, 'ProxyServer', 0, reg.REG_SZ, proxy_server)

                # 设置例外（不走代理的地址）
                exceptions = '<local>,localhost,' + ','.join(override_exceptions)
                reg.SetValueEx(key, 'ProxyOverride', 0, reg.REG_SZ, exceptions)

        print("✅ 代理设置已更新！")
    except Exception as e:
        print("❌ 修改代理失败:", str(e))